package com.alt.manager;

import java.util.Collection;
import java.util.HashMap;
import android.annotation.SuppressLint;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
import android.util.Log;

@SuppressLint("UseSparseArrays")
public class ALTSoundMgr {
	public static final String TAG = "SoundManager";
	public static final int SOUND_CART_UPDATED = 1;

	int soundRes[] = { 0 };//{ R.raw.sound_cart_updated };

	private final int SOUNDPOOL_STREAMS = 4;
	private Context m_Context = null;
	private SoundPool m_SoundPool = null;
	private HashMap<Integer, Integer> m_SoundPoolMap;

	public void init(Context context) {
		// if(m_Context == null)
		{
			m_Context = context;
			Log.v(TAG, "[SoundManager] Init");
			release();

			m_SoundPool = new SoundPool(SOUNDPOOL_STREAMS,
					AudioManager.STREAM_MUSIC, 0);
			m_SoundPoolMap = new HashMap<Integer, Integer>();
			for (int index = 0; index < (soundRes.length >> 1); ++index) {
				m_SoundPoolMap
						.put(soundRes[index * 2], m_SoundPool.load(m_Context,
								soundRes[index * 2 + 1], 1));
				Log.v(TAG, "[SoundManager] Load: " + soundRes[index * 2]
						+ " ID: " + m_SoundPoolMap.get(soundRes[index * 2]));
			}
			Log.v(TAG, "[SoundManager] Init Finished");
		}
	}

	public void play(int sound) {
		if (m_SoundPool != null) {
			Log.d(TAG, "Playing Sound " + sound);
			AudioManager mgr = (AudioManager) m_Context
					.getSystemService(Context.AUDIO_SERVICE);
			int streamVolume = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
			Integer soundId = m_SoundPoolMap.get(sound);
			if (soundId != null) {
				m_SoundPool.setLoop(soundId, 0);
				m_SoundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);
			}
		}
	}

	public void ouload() {
		if (m_SoundPoolMap != null) {
			Collection<Integer> soundIds = m_SoundPoolMap.values();
			for (int soundId : soundIds) {
				m_SoundPool.unload(soundId);
				Log.d(TAG, "[SoundManager] Destroy Sound Id " + soundId);
			}
			m_SoundPoolMap = null;
		}
	}

	public void release() {
		if (m_SoundPool != null) {
			// ouload();
			Log.d(TAG, "Closing SoundPool");
			m_SoundPool.release();
			m_SoundPool = null;
			Log.d(TAG, "SoundPool Closed");
		}
	}
}
